# -*- coding: utf-8 -*-
'''
Created on 2012-10-1

@author: Leon
'''
from flask import current_app, g
from models import Firm, Product, Tag
from common import query_db, exdb
from datetime import datetime
import random, feedparser


#获取在yml中的随机产品,以每日进行缓存,一天更新一次
def getTodayProducts():
    #检查原有集合
    if (not hasattr(current_app, 'yml_todayproducts') or current_app.yml_todayproducts[0] != datetime.now().date()):
        current_app.yml_todayproducts = (datetime.now().date(), random.sample(current_app.yml_products, 9))
    return current_app.yml_todayproducts[1]


#云计算新闻抓取,一天更新一次
def getTodayNews():
    if (not hasattr(current_app, 'yml_todaynews') or current_app.yml_todaynews[0] != datetime.now().date()):
        newfeed = feedparser.parse(current_app.config['NEWS_RSS_URL'])
        current_app.yml_todaynews = (datetime.now().date(), newfeed.entries)
        #赋值日期
        for new in current_app.yml_todaynews[1]:
            new.yml_date = datetime(new.published_parsed.tm_year, new.published_parsed.tm_mon,
                                    new.published_parsed.tm_mday).date()
    return current_app.yml_todaynews[1]


#查询产品视图 关键字
def queryProducts(keyword):
    #搜索关键字 name ename tag
    if keyword:
        keyword = u'%{0}%'.format(keyword)
        sql = 'select * from Product where name like :name or eName like :eName or featureTags like :featureTags '
        rows = query_db(sql, {'name': keyword, 'eName': keyword, 'featureTags': keyword})
        result = []
        for row in rows:
            result.append(Product(row))
        return result

#tag查询
def queryProductsByTag(tag):
    if tag:
        keyword = u'%{0}%'.format(tag)
        sql = 'select * from Product where featureTags like :tag '
        rows = query_db(sql, {'tag': tag})
        result = []
        for row in rows:
            result.append(Product(row))
        return result

#cate查询
def queryProductsByCate(cate):
    if cate:
        cate = u'%{0}%'.format(cate)
        sql = 'select * from Product where categoryTags like :cate '
        rows = query_db(sql, {'cate': cate})
        result = []
        for row in rows:
            result.append(Product(row))
        return result


#
def getFreshProduct(pid):
    sql = 'select * from Product where id=:pid'
    rows = query_db(sql, {'pid': pid})
    return Product(rows[0])



#获取全部产品
def getAllProducts():
    sql = ' select * from Product '
    rows = query_db(sql)
    result = []
    for row in rows:
        result.append(Product(row))
    return result


#获取单个产品视图
def getProduct(id):
    #sql='select * from Product where id=:id'
    for p in current_app.yml_products:
        if p.id == id:
            return p

#获取单个产品视图
def getProductByMark(mark):
    #sql='select * from Product where mark=:mark'
    for p in current_app.yml_products:
        if p.mark == mark:
            return p

#获取单个产品视图
def getProductByName(name):
    #sql='select * from Product where name=:name'
    for p in current_app.yml_products:
        if p.name == name:
            return p


#获取所有标签 依对应数量排名
def getAllTags(count):
    result = []
    sql = 'select * from tag order by count desc'
    for row in query_db(sql):
        result.append(Tag(row))
    return result


#以下 admin 方法=====================================

#添加产品
def addProduct(fid, name, eName, logoUrl, pageUrl, categoryTags, featureTags, caption):
    sql = 'insert into Product (firmID,name,eName,categoryTags,featureTags,logoUrl,pageUrl,caption,status,latestUpdateTime,creationTime)' \
          ' values (:firmID,:name,:eName,:categoryTags,:featureTags,:logoUrl,:pageUrl,:caption,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)'
    exdb(sql, {'firmID': fid, 'name': name, 'eName': eName, 'logoUrl': logoUrl, 'pageUrl': pageUrl,
               'categoryTags': categoryTags, 'featureTags': featureTags, 'caption': caption})


#更新产品
def updateProduct(pid, name, eName, logoUrl, pageUrl, categoryTags, featureTags, caption):
    sql = 'update Product set name=:name,eName=:eName,categoryTags=:categoryTags,featureTags=:featureTags,' \
          ' logoUrl=:logoUrl,pageUrl=:pageUrl,caption=:caption,latestUpdateTime=CURRENT_TIMESTAMP where id=:pid'
    exdb(sql, {'pid': pid, 'name': name, 'eName': eName, 'logoUrl': logoUrl, 'pageUrl': pageUrl,
               'categoryTags': categoryTags, 'featureTags': featureTags, 'caption': caption})